package com.mehdiuz.backend.commons.handler;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mehdiuz.backend.commons.utils.JwtUtils;
import com.mehdiuz.backend.role.entity.CustomUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JedisPool jedisPool;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if("/admin/system/index/login".equals(request.getRequestURI()) ||
                "/api/captcha/pullCaptcha".equals(request.getRequestURI()) || "/api/captcha/checkCaptcha".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }
        Jedis jedis = jedisPool.getResource();
        String token = request.getHeader("token");
        CustomUser customUser = null;
        String s1 = "";
        if(StringUtils.isNotBlank(token)){
            String s = JwtUtils.getUsername(token);
            if(StringUtils.isNotBlank(s)){
                try {
                    s1 = jedis.get("login" + s);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    jedis.close();
                }
                if(StringUtils.isNotBlank(s1)){
                    customUser = JSONObject.parseObject(s1, CustomUser.class);
                }
            }
        }else {
            filterChain.doFilter(request,response);
            return;
        }
        if(customUser!=null){
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(customUser,null,customUser.getAuthorities()));
            filterChain.doFilter(request,response);
        }else {
            filterChain.doFilter(request,response);
            return;
        }
    }
}
